<?php
class newsController extends Controller{

	private $_model;

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to access 'index' and 'view' actions.
				'actions'=>array('index','error','view','tag'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated users to access all actions
				'actions'=>array('create','edit','refresh'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
				'message'=>'您无权访问该页面',
			),
		);
	}
	public function actionIndex(){
		$this->pageTitle = '首页';
		$criteria = new CDbCriteria(array(
			'order'=>'update_time DESC',
			'limit'=>60,
		));
		if(!Yii::app()->user->isGuest){//登录用户
			$criteria->with = array('actions');
			$upper = Upper::getUpper(Yii::app()->user->id,'self');
			if(empty($upper)){
				$upperIds = Shell::initTenUpper();
				$upper = Upper::getUpper(Yii::app()->user->id,'self');
			}else{
				foreach($upper as $val){
					$upperIds[] = $val->user_id;
				}
			}
			$criteria->addInCondition("t.user_id",$upperIds,'');
			$dataProviderNews=new CActiveDataProvider('News', array(
				'criteria'=>$criteria,
				'pagination'=>array(
					'pageSize'=>20,
				),
			));
			$fans = Fans::getUserByFansUid(Yii::app()->user->id,12);
			$this->render('index',array('dataProvider'=>$dataProviderNews,'upper'=>$upper,'fans'=>$fans));
		}else{//未登录用户
			$upper = Upper::recommendUpper();
			foreach($upper as $handle){
				$upperIds[] = $handle->user_id;
			}
			$criteria->addInCondition("t.user_id",$upperIds,'');
			//$news = News::model()->findAll("user_id in ($upperId) order by post_time DESC");
			$dataProviderNews=new CActiveDataProvider('News', array(
				'criteria'=>$criteria,
				'pagination'=>array(
					'pageSize'=>20,
				),
			));
			$this->render('index_nologin',array('dataProvider'=>$dataProviderNews,'upper'=>$upper));
		}
	}

	
	public function actionCreate()
    {
		 $model = new News;
		 if(isset($_POST['ajax']) && $_POST['ajax'] === 'news-form' ){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		 }
		// dbg($_POST);
		 if(isset($_POST['News'])){
			$model->attributes = $_POST['News'];
			//dbg($_POST['News']);
			//$model->news_thumb = isset($_POST['News']['news_thumb']) ? $_POST['News']['news_thumb'] : '';
			//Yii::import('Curl');
			//$model->news_thumb = Thumb::grabThumb($model->link_url);
			if($model->createNews($model)){
				$news_id = $model->primaryKey;
				//写入到一个文件中，让其去自动抓取默认照片
				CacheFile::cacheThumb($news_id,$model->link_url);
				if($_POST['News']['is_plugin']){
					echo "<script type='text/javascript'>window.close();</script>";
				}else{
					$this->redirect("/news/$news_id");
				}
				exit;
			}else{
				if($_POST['News']['is_plugin']){
					echo "<script type='text/javascript'>window.close();</script>";exit;
				}
				throw new CHttpException(400,$model->getErrors());
				exit;
			}
			
		 }
		
        $this->render('create',array('model'=>$model));
    }

	public function actionView(){
		
		$news = $this->loadModel();
		$news->tagLinks = $news->getTagLinks();
		$comments = $this->addComments($news);
		$criteria = new CDbCriteria(array(
			'order'=>'comment_time DESC',
			'condition'=>'news_id=:news_id',
			'params'=>array(':news_id'=>$news->news_id),
		));
		$dataProvider = new CActiveDataProvider('Comments',array(
			'pagination'=>array('pageSize'=>5),
			'criteria'=>$criteria
		));
		//同样喜欢这个分享的赞友
		$userLikes = Actions::model()->findAll("news_id=".$news->news_id . " order by action_time DESC");
		//作者信息
		$user = User::model()->findByPk($news->user_id);
		$userTag = explode(' ', $user->news_tag_name);
		$myTag = '';
		$newsTag = array();
		if(!empty($news->tagLinks))
			foreach($news->tagLinks as $tag){
				$newsTag[] = strip_tags($tag['tag_name']);
			}
		if(!empty($userTag))
			foreach($userTag as $tag){
				if(in_array($tag,$newsTag)){
					$myTag .= "<a href='javascript:' class='taged'>$tag</a> ";
				}else{
					$myTag .= "<a href='javascript:' class='tagging tagbtn'>$tag</a> ";
				}
			}
		//作者的粉丝
		//$fans = Fans::model()->findAll("user_id=".$news->user_id . " and is_outdate='no' order by fans_time DESC");
		$fans = new CActiveDataProvider('Fans',array(
			'criteria'=>array(
				'condition'=>"user_id=".$news->user_id . " and is_outdate = 'no'",
				'order'=>'fans_time DESC'
			),
			'pagination'=>array('pageSize'=>12)
		));
		$this->render('view',array('fans'=>$fans,'user'=>$user,'userLikes'=>$userLikes,'model'=>$news,'comment'=>$comments,'dataProvider'=>$dataProvider,'myTag'=>$myTag));
		//dbg($news->user_id);
	}
	public function loadModel(){
		$news_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
		if(!$news_id){
			throw new CHttpException(404,'您访问的页面不存在');
		}
		if($this->_model===null)
		{
			$this->_model=News::model()->findByPk($news_id);
			if($this->_model===null)
				throw new CHttpException(404,'您访问的页面不存在.');
		}
		return $this->_model;
	}
	public function addComments($news){
		$comment = new Comments;
		if(isset($_POST['ajax']) and $_POST['ajax'] === 'comment-form'){
			echo CActiveForm::validate($comment);
			Yii::app()->end();
		}
		if(isset($_POST['Comments'])){
			$comment->attributes = $_POST['Comments'];
			$comment->news_id = $news->news_id;
			$comment->comment_time = time();
			$comment->user_id = Yii::app()->user->id;
			$comment->user_name = Yii::app()->user->name;
			if($comment->validate() and $comment->save()){
				//更新评论数
				News::model()->updateCounters(array('comment_num'=>1),'news_id=:news_id',array(':news_id'=>$news->news_id));
				User::model()->updateCounters(array('comment_num'=>1),'user_id=:user_id',array(':user_id'=>$comment->user_id));
				Yii::app()->user->setFlash('submitNewsComment','恭喜您，评论成功！');
				$this->refresh();
			}else
				throw new CHttpException(400,$comment->getErrors());
		}
		return $comment;
	}
	public function actionEdit(){
		$news = new News;
		$newsID = (int)NC::_g('id','');
		$data['site_title'] = NC::_p('site_title','');
		$data['news_desc'] = NC::_P('news_desc','');
		$data['news_tag'] = NC::_p('news_tag','');
		if($news->updateByPk($newsID,$data)){
			//nc_user表(update)
			User::updateByNews($data['news_tag']);
			//更新tag
			Tags::model()->updateTagUseNum('', $data['news_tag'],$newsID);
			$this->redirect("/favorites/discover#list_favorites_$newsID");
		}else{
			$this->redirect("/favorites/discover#list_favorites_$newsID");
		}
	}
	public function actionTag(){
		$newsID = NC::_g('id','');
		if(!$newsID)
			throw new CHttpException('非法操作');
		$tag = $tags = NC::_p('news_tag','');
		if(!$tag)
			$this->redirect("/news/$newsID");
		$new = News::model()->findByPk($newsID);
		$tags .= $new->news_tag;
		$tags = explode(' ',$tags);
		array_unique($tags);
		$tags = implode(' ',$tags);
		$data['news_tag'] = $tags;
		if($new->updateByPk($newsID,$data)){
			//nc_user表(update)
			User::updateByNews($tag);
			//更新tag
			Tags::model()->updateTagUseNum($new->news_tag, $tag,$newsID);
			$this->redirect("/news/$newsID");
		}else{
			$this->redirect("/news/$newsID");
		}
	}
	public function actionRefresh(){
		if(NC::_g('f','new') == 'upper'){
			$upper = Upper::getUpper(Yii::app()->user->id,'self');
			 foreach($upper as $val):
				$this->renderPartial('_share',array('upper'=>$val));
			 endforeach;
			Yii::app()->end();
		}
		$criteria = new CDbCriteria(array(
			'order'=>'update_time DESC',
			'limit'=>60,
		));
		$criteria->with = array('actions');
		$upper = Upper::getUpper(Yii::app()->user->id,'self');
		if(count($upper) < 10){
			$upperIds = Shell::initTenUpper(Yii::app()->user->id);
		}else{
			foreach($upper as $val){
				$upperIds[] = $val->user_id;
			}
		}
		$criteria->addInCondition("t.user_id",$upperIds,'');
		$dataProviderNews=new CActiveDataProvider('News', array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>20,
			),
		));
		$this->widget('zii.widgets.CListView',array(
				'dataProvider'=>$dataProviderNews,
				'itemView'=>'_list',
				//'viewData'=>array('comments'=>$model->comments),
				'emptyText'=>'还没有发布新闻.',
				'enablePagination'=>false,
		));
	}
}